package org.lyh.gift.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import io.seata.spring.annotation.GlobalTransactional;
import org.lyh.gift.client.LoginUserFeignClient;
import org.lyh.gift.domain.LoginUser;
import org.lyh.gift.domain.User;
import org.lyh.gift.mapper.UserMapper;
import org.lyh.gift.pojo.dto.UserDTO;
import org.lyh.gift.service.IUserService;
import org.lyh.gift.util.AjaxResult;
import org.lyh.gift.util.BitStatesUtils;
import org.lyh.gift.util.encrypt.MD5;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.UUID;

/**
 * <p>
 * 会员登录账号 服务实现类
 * </p>
 *
 * @author lyh
 * @since 2024-09-25
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    private LoginUserFeignClient loginUserFeignClient;
    @GlobalTransactional(rollbackFor = Exception.class)
    @Override
    public void register(UserDTO userDTO) {
        //数据校验
        checkData(userDTO);
        //数据封装
        User user=userBean(userDTO);
        LoginUser loginUser = loginUserBean(user);
        //发起远程调用
        AjaxResult ajaxResult = loginUserFeignClient.addOrUpdate(loginUser);
        if (ajaxResult.isSuccess()){
//            System.out.println(1/0);
            Object resultObj = ajaxResult.getResultObj();
            user.setLoginId(Long.valueOf(resultObj.toString()));
            //user表新增记录
            super.insert(user);
        }
    }

    private LoginUser loginUserBean(User user) {
        LoginUser loginUser = new LoginUser();
        BeanUtil.copyProperties(user,loginUser);
        loginUser.setUsername(user.getPhone());
        loginUser.setType(LoginUser.USER);
        return loginUser;
    }

    private User userBean(UserDTO userDTO) {
        User user = new User();
        user.setPhone(userDTO.getPhone());
        String salt = UUID.randomUUID().toString();
        user.setSalt(salt);
        user.setPassword(MD5.getMD5(userDTO.getPassword()));
        user.setCreateTime(new Date().getTime());
        //给用户添加状态
        long l = BitStatesUtils.addState(BitStatesUtils.OP_REGISTED, BitStatesUtils.OP_ACTIVED);
        long state = BitStatesUtils.addState(l, BitStatesUtils.OP_AUTHED_PHONE);
        user.setBitState(state);
        return user;
    }

    private void checkData(UserDTO userDTO) {
    }
}
